from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.conf import settings
from .services import DeepSeekRecommendationService
from analytics.models import UserBehavior
import logging

logger = logging.getLogger('recommendation')

# Create your views here.

@login_required
def simple_recommendations(request):
    """获取用户的推荐盲盒并展示（简化版，避免OpenAI调用）"""
    user_id = request.user.user_id
    
    # 记录用户查看了推荐页面
    UserBehavior.objects.create(
        user_id=user_id,
        action_type='view',
        object_type='recommendation_page',
        object_id=0,
        url=request.path
    )
    
    # 创建一些预设的盲盒推荐数据，避免调用OpenAI
    from django.db import connection
    
    # 直接从数据库获取一些热门盲盒
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT box_id, name, image_url, category, original_price, discount_price
            FROM tb_blind_box
            WHERE status = 1
            ORDER BY sales DESC
            LIMIT 8
        """)
        
        boxes = []
        for row in cursor.fetchall():
            boxes.append({
                'recommendation_id': None,
                'box_id': row[0],
                'box_name': row[1],
                'box_image': row[2],
                'category': row[3],
                'price': float(row[4]) if row[4] else 0.0,
                'discount_price': float(row[5]) if row[5] else 0.0,
                'theme': '精选盲盒',  # 默认主题
                'score': 0.95,  # 预设的分数
                'rank': len(boxes) + 1,
                'reason': '基于您的历史喜好推荐',
                'stock': 10
            })
    
    logger.info(f"为用户 {user_id} 生成了 {len(boxes)} 个简化推荐")
    
    return render(request, 'recommendation/recommendations.html', {
        'recommendations': boxes,
        'title': '为您推荐（简化版）'
    })

@login_required
def user_recommendations(request):
    """获取用户的推荐盲盒并展示"""
    # 由于OpenAI客户端问题，先重定向到简化版推荐
    return redirect('recommendation:simple_recommendations')
    
    # 以下是原代码，暂时注释掉
    """
    user_id = request.user.user_id
    
    # 创建推荐服务实例
    service = DeepSeekRecommendationService()
    
    # 获取推荐结果
    recommendations = service.get_user_recommendations(user_id)
    
    # 记录用户查看了推荐页面
    UserBehavior.objects.create(
        user_id=user_id,
        action_type='view',
        object_type='recommendation_page',
        object_id=0,
        url=request.path
    )
    
    return render(request, 'recommendation/recommendations.html', {
        'recommendations': recommendations,
        'title': '为您推荐'
    })
    """

@login_required
def recommendation_api(request):
    """推荐API，返回JSON格式的推荐数据"""
    user_id = request.user.user_id
    limit = int(request.GET.get('limit', 8))
    
    # 创建推荐服务实例
    service = DeepSeekRecommendationService()
    
    # 获取推荐结果
    recommendations = service.get_user_recommendations(user_id, limit=limit)
    
    # 记录用户查看了推荐
    UserBehavior.objects.create(
        user_id=user_id,
        action_type='view',
        object_type='recommendation_api',
        object_id=0,
        url=request.path
    )
    
    return JsonResponse({
        'success': True,
        'recommendations': recommendations
    })

@login_required
@require_POST
def log_recommendation_click(request, recommendation_id):
    """记录用户点击了推荐商品"""
    # 创建推荐服务实例
    service = DeepSeekRecommendationService()
    
    # 记录点击
    success = service.log_recommendation_click(recommendation_id)
    
    # 记录用户行为
    if success:
        UserBehavior.objects.create(
            user_id=request.user.user_id,
            action_type='click',
            object_type='recommendation',
            object_id=recommendation_id,
            url=request.path
        )
    
    # 获取要跳转的盲盒ID
    box_id = request.POST.get('box_id')
    
    if box_id:
        # 跳转到盲盒详情页面
        return redirect('blindbox:detail', box_id=box_id)
    else:
        # 返回JSON响应
        return JsonResponse({
            'success': success
        })

@login_required
def generate_recommendations(request):
    """管理员手动触发推荐生成"""
    # 检查是否为管理员
    if not request.user.is_admin:
        return JsonResponse({
            'success': False,
            'error': '权限不足'
        }, status=403)
    
    # 获取参数
    user_id = request.GET.get('user_id')
    if user_id:
        user_id = int(user_id)
    
    # 创建推荐服务实例
    service = DeepSeekRecommendationService()
    
    # 生成推荐
    result = service.generate_user_recommendations(user_id=user_id)
    
    return JsonResponse({
        'success': True,
        'count': result
    })
